package com.xiaocikuai.smallchunks.controller.Card;

import com.xiaocikuai.smallchunks.entity.Card.CardChunks;
import com.xiaocikuai.smallchunks.entity.Transaction.VirtualOrder;
import com.xiaocikuai.smallchunks.entity.User.User;
import com.xiaocikuai.smallchunks.mapper.Card.CardChunksMapper;
import com.xiaocikuai.smallchunks.mapper.Transaction.VirtualOrderMapper;
import com.xiaocikuai.smallchunks.service.Card.ICardChunksService;
import com.xiaocikuai.smallchunks.utils.JWTservice.JwtService;
import com.xiaocikuai.smallchunks.utils.resultd.Resultd;
import jakarta.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.*;
import com.xiaocikuai.smallchunks.utils.DateTime.dateTimeService;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVRecord;

@Api(tags = "卡片管理控制器")
@RestController
@RequestMapping("/api/card/chunks")
@CrossOrigin
public class CardChunksController {

    @Resource
    private CardChunksMapper cardChunksMapper;

    @Resource
    private dateTimeService dateTimeService;

    @Resource
    private ICardChunksService cardChunksService;

    @Resource
    private VirtualOrderMapper virtualOrderMapper;
    @Resource
    private JwtService jwtService;

    @ApiOperation(value = "卡片文件上传")
    @PostMapping("/upload")
    @ResponseBody
    @ApiImplicitParams({
            @ApiImplicitParam(name = "productId", value = "产品 ID", required = true, dataType = "int", paramType = "query")
    })
    public ResponseEntity<String> uploadFile(MultipartHttpServletRequest request,
                                             @RequestParam("productId") int productId) {
        Iterator<String> itr = request.getFileNames();
        MultipartFile file = request.getFile(itr.next());
        if (file != null) {
            try {
                String originalFilename = file.getOriginalFilename();
                if (originalFilename != null && (originalFilename.endsWith(".xls") || originalFilename.endsWith(".xlsx") || originalFilename.endsWith(".csv"))) {
                    try {
                        parseAndSave(file.getInputStream(), productId);
                        return ResponseEntity.ok("File uploaded successfully.");
                    } catch (IOException e) {
                        e.printStackTrace();
                        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to parse file.");
                    } catch (Exception e) {
                        e.printStackTrace();
                        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to insert data into database.");
                    }
                } else {
                    return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Only Excel or CSV files are allowed.");
                }
            } catch (Exception e) {
                e.printStackTrace();
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to upload file.");
            }
        } else {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("No file uploaded.");
        }
    }

    @ApiOperation(value = "卡片文件上传")
    @PostMapping("/uploadssss")
    @ResponseBody
    @ApiImplicitParams({
            @ApiImplicitParam(name = "productId", value = "产品 ID", required = true, dataType = "int", paramType = "query")
    })
    public ResponseEntity<String> uploadFilessss(MultipartHttpServletRequest request) {
        Iterator<String> itr = request.getFileNames();
        MultipartFile file = request.getFile(itr.next());
        if (file != null) {
            try {
                String originalFilename = file.getOriginalFilename();
                if (originalFilename != null && (originalFilename.endsWith(".xls") || originalFilename.endsWith(".xlsx") || originalFilename.endsWith(".csv"))) {
                    try {
                        parseAndave(file.getInputStream());
                        return ResponseEntity.ok("File uploaded successfully.");
                    } catch (IOException e) {
                        e.printStackTrace();
                        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to parse file.");
                    } catch (Exception e) {
                        e.printStackTrace();
                        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to insert data into database.");
                    }
                } else {
                    return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Only Excel or CSV files are allowed.");
                }
            } catch (Exception e) {
                e.printStackTrace();
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to upload file.");
            }
        } else {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("No file uploaded.");
        }
    }

    @ApiOperation(value = "卡片相关数据的解析和存储")
    public void parseAndSave(InputStream inputStream, int productId) throws IOException {

        InputStreamReader reader = new InputStreamReader(inputStream);
        Iterable<CSVRecord> records = CSVFormat.DEFAULT.parse(reader);

        List<CardChunks> cardChunks = new ArrayList<>();
        int rowNum = 0; // 记录行号
        for (CSVRecord record : records) {
            String front = record.get(0); // 第一列
            String back = record.get(1); // 第二列
            String frontHl = record.get(2); // 第三列
            String backHl = record.get(3); // 第四列

            // 创建CardChunk对象并添加到列表中
            CardChunks cardChunk = new CardChunks();
            cardChunk.setWordId(null); // 您需要自己处理关联单词id的逻辑
            cardChunk.setFront(front);
            cardChunk.setBack(back);
            cardChunk.setFrontHl(frontHl);
            cardChunk.setBackHl(backHl);
            cardChunk.setProductId(productId);
            cardChunk.setCreateTime(LocalDateTime.now());
            cardChunk.setUpdateTime(null); // 如果需要设置更新时间，可以根据实际情况进行设置
            cardChunk.setSort(rowNum++); // 使用行号作为排序值
            cardChunks.add(cardChunk);
        }

        // 将解析得到的数据插入数据库
        for (CardChunks cardChunk : cardChunks) {
            // 执行插入操作，这里您需要调用您的数据访问层方法将数据插入数据库
            if (cardChunksMapper.insertCardChunk(cardChunk)) {
                // 这里假设您有一个名为cardChunkRepository的JPA Repository
                // cardChunkRepository.save(cardChunk);
            }
        }
    }




    @ApiOperation(value = "卡片收藏")
    @PostMapping("/collect")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "授权令牌", required = true, dataType = "String", paramType = "header"),
            @ApiImplicitParam(name = "card", value = "卡片信息", required = true, dataType = "CardChunks", paramType = "body")
    })
    public Resultd collections(@RequestHeader("Authorization") String token, @RequestBody CardChunks card) {
        User user = jwtService.deconstruction(token);
        int mode = card.getSort();
        int cid = card.getCid();
        LocalDateTime time = dateTimeService.getCurrentDateTime();
        if (mode == 0) {
            if (cardChunksService.collectionAdd(user.getUid(), cid, time)) {
                return Resultd.ok().data("info", "收藏成功");
            } else
                return Resultd.error().data("error", "收藏失败");
        } else if (mode == 1) {
            if (cardChunksService.collectionDel(user.getUid(), cid)) {
                return Resultd.ok().data("info", "取消收藏");
            } else
                return Resultd.error().data("error", "取消失败");

        } else
            return Resultd.error().data("error", "404-收藏 mode 错误");
    }



    /**
     * 收藏卡片展示
     *
     * @param token
     * @return
     */
    @PostMapping("/collectList")
    public Resultd collectList(@RequestHeader("Authorization") String token, @RequestBody CardChunks cardChunks) {
        int pid = cardChunks.getProductId();
        Integer uid = jwtService.deconstruction(token).getUid();
        List<CardChunks> list= cardChunksService.collectList(pid,uid);
        if (list.isEmpty()) {
            return Resultd.error().data("info", "收藏夹为空");
        }

        return Resultd.ok().data("info", list);
    }


    @ApiOperation(value = "卡片相关数据的解析和存储")
    public void parseAndave(InputStream inputStream) throws IOException {

        InputStreamReader reader = new InputStreamReader(inputStream);
        Iterable<CSVRecord> records = CSVFormat.DEFAULT.parse(reader);

        List<VirtualOrder> virtualOrders = new ArrayList<>();

        int rowNum = 0; // 记录行号
        for (CSVRecord record : records) {
            String front = record.get(0); // 第一列
            String back = record.get(1); // 第二列


            // 创建CardChunk对象并添加到列表中
            VirtualOrder virtualOrder = new VirtualOrder();
            virtualOrder.setUid(Integer.parseInt(front));
            virtualOrder.setPid(Integer.parseInt(back));
            virtualOrder.setUseType(null);
            virtualOrder.setStatus(1);
            virtualOrder.setCreateTime(LocalDateTime.now());
            virtualOrder.setIfdis(0);
            virtualOrders.add(virtualOrder);
        }

        // 将解析得到的数据插入数据库
        for (VirtualOrder virtualOrder : virtualOrders) {
            // 执行插入操作，这里您需要调用您的数据访问层方法将数据插入数据库
            if (cardChunksMapper.insertCardChunk1(virtualOrder)) {

            }
        }
    }





}

